var redis = require("redis");
var redis_client = redis.createClient();

redis_client.on("error", function (err) {
    console.log("Error " + err);
});

var m_db_session = null;

var refMgr = require('./referenceMgr').GetInstance();

function Initialize(serverApp, db_session) {

    serverApp.post('/PV/:common', CommonHandler);
    serverApp.post('/PV/RegisterAccount', RegisterAccount);
    serverApp.post('/PV/Login', Login);
    
    m_db_session = db_session;
}

function CommonHandler(request, response, next) {

    next();
}

function RegisterAccount(request, response) {

    //generate id
    var newID = 'vs';
    var time = new Date().getDate() / 1000;
    newID += time + Math.floor(Math.random() * 10000) + 1;
    
    //generate pwd
    var newPWD = Math.floor(Math.random() * 10000) + 1;
    
    //set response
    var result = { 'result':true, 'vs_id':newID, 'vs_pwd':newPWD };
    
    var completion = function(error, result, queryHandle){
        
        response.writeHead( 200, {"Content-Type": "text/plain"} );
        if( error ){
            console.log( error );
        }
        else{
            var ack = JSON.stringify( result );
            console.log( ack );
            response.write( ack );
        }
        response.end();
    };
    
    m_db_session.query('insert into pv_account (vs_id,vs_pwd) values (?,?)', [newID,newPWD], completion );
}

function Login(request, response) {

    var reference = global.refMgr.GetRefArea( 1 );
    console.log( reference.id );
    
    //var value_a = request.param('a');
    response.writeHead( 200, {"Content-Type": "text/plain"} );
    response.write( "express upload handler" );
    response.end();
}

exports.Initialize = Initialize;